﻿using System;
using Ninject;
using SydEnergiPrototype.Logic;
using SydEnergiPrototype.Model;

namespace SydEnergiPrototype.DataAccess
{
    public class DetectAddressChangesDataStore : IMemoryDataStore
    {
        public void PersistCabinetId(string id)
        {
            _itsDataStore.PersistCabinetId(id);
        }

        public void Persist(IEntry entry)
        {

            if(!entry.EntryAddress.Equals(_originalAddress) && _originalAddress != null)
            {
                entry.EntryAddress = new MarkedAddress(Copier.DeepCopy(_originalAddress), entry.EntryAddress);
                _originalAddress = null;
            }
            
            _itsDataStore.Persist(entry);
        }

        public void Persist(Cabinet cabinet)
        {
            _itsDataStore.Persist(cabinet);
        }

        public string RetrieveCabinetId()
        {
            return _itsDataStore.RetrieveCabinetId();
        }

        public IEntry RetrieveEntry()
        {
            var entry = _itsDataStore.RetrieveEntry();
            _originalAddress = Copier.DeepCopy(entry.EntryAddress);
            return entry;
        }

        public Cabinet RetrieveCabinet()
        {
            return _itsDataStore.RetrieveCabinet();
        }

        private readonly IMemoryDataStore _itsDataStore;
        private static IAddress _originalAddress;

        [Inject]
        public DetectAddressChangesDataStore(IMemoryDataStore memoryDataStore)
        {
            if(memoryDataStore == null)
                throw new ArgumentNullException("memoryDataStore");
            _itsDataStore = memoryDataStore;
        }
    }
}
